<template>
    <div>
        <!--登录组件-->
        <!--form数据绑定-->
        <el-form ref="form" :model="form" :rules="rules" class="login-box">
            <h2 class="login-title">宠物信息管理系统</h2>
            <!--用户名-->
            <el-form-item label="账号" prop="username">
                <el-input type="text" placeholder="请输入用户名" v-model="form.username"></el-input>
            </el-form-item>
            <!--密码-->
            <el-form-item label="密码" prop="u_password">
                <el-input type="password" placeholder="请输入密码" v-model="form.u_password"></el-input>
            </el-form-item>
            <!--按钮-->
            <el-form-item>
                <div class = "login-btn">
                    <el-button type="primary" @click="submitForm('form')">登录</el-button>
                    <el-button type="info" @click="resetLoginFrom">重置</el-button>
                </div>
            </el-form-item>

        </el-form>
    </div>
</template>

<script>

export default ({
    //name:"Login",
    data(){
        return{
            //登录表单的数据绑定对象
            form:{
                username:'',
                u_password:'',
            },
            //表单验证规则对象
            rules:{
                username: [{ 
                    required: true,
                    message: '请输入用户名',
                    trigger: 'blur' 
                }],
                u_password: [
                    { 
                    required: true,
                    message: '请输入密码',
                    trigger: 'blur' 
                },
                { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                ],
            }
        }
    },
    methods:{
        //点击重置按钮，重置登录
        resetLoginFrom() {
            this.$refs.form.resetFields();
        },
        //数据预验证
        submitForm(formName) {
        //async异步
        this.$refs[formName].validate(async valid => {
            //console.log(valid);
            if(!valid) return;
            //const {}解构 message弹框提示
            const {data:res} = await this.$http.post("system/apis/login",this.form);
            if(res.code == 30000) {
                this.$message.error("没有此用户");
                return;
            }
            if(res.code == 30001) {
                this.$message.error("账户或密码错误");
                return;
            }
            if(res.code == 20000) {
                this.$message.success("登录成功");
                //window.sessionStorage.setItem("token",res.data.token);
                this.$router.push("/home");
                return;
            }
            this.$message.error("后台错误");
        });
      },
    }
    
})
</script>

<style>
.login-box {
  width: 350px;
  margin: 40px auto;
  border: 1px solid #081f55;
  padding: 50px;
  border-radius: 30px;
  box-shadow: 0 2px 12px 0 rgba(77, 33, 148, 0.1);
}

.login-title {
  margin-top: 100px;
  text-align: center;
}

.login-btn {
    text-align: center;
}

</style>
